/**
 * 
 */
package org.swing.utility.jai.util;
import java.awt.image.renderable.ParameterBlock;

import javax.media.jai.InterpolationNearest;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
/**
 * @author Quynh Nhu
 *
 */
public class ScaleImage
{
  public static PlanarImage scaleImage(PlanarImage orig, int maxW, int maxH) 
  {
    double hScale = 1.0F, wScale = 1.0F;
    Double dScale;
    if (orig != null)
    {
      int w = orig.getWidth();
      int h = orig.getHeight();

//      if (w > maxW || h > maxH)
//      {
//        if (w > maxW)
          wScale = (double) maxW / (double) w;

        //if (h > maxH)
          hScale = (double) maxH / (double) h;

        dScale = new Double( wScale > hScale ? hScale : wScale);
        float sc = dScale.floatValue();

        ParameterBlock pb = new ParameterBlock();
        pb.addSource(orig);
        //pb.add(null).add(null).add(null).add(null).add(null);
        pb.add(sc).add(sc).add(0.0F).add(0.0F).add(new InterpolationNearest());

        //RenderedImage ren = (RenderedImage) orig;
        //RenderingHints xx = new RenderingHints(null);
        //SubsampleAverageDescriptor sad = new SubsampleAverageDescriptor();

        //RenderedOp ro = sad.create(ren, dScale, dScale, null);

        //PlanarImage planrImg = ro.getRendering();
        PlanarImage planrImg = JAI.create("scale", pb);

        return planrImg;
//      }
    }
    return (orig);
  }
}
